package com.github.icloudpay.pay.core.service.refund.alipay.service;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.github.icloudpay.pay.core.feign.PayChannelConfigFeign;
import com.github.icloudpay.pay.core.inter.RefundService;
import com.github.icloudpay.pay.core.service.pay.alipay.util.AliPayConfig;
import com.github.wxiaoqi.security.common.admin.pay.request.RefundRequest;
import com.github.wxiaoqi.security.common.admin.pay.response.RefundResponse;
import com.github.wxiaoqi.security.common.msg.ResponseCode;
import com.github.wxiaoqi.security.common.util.EntityUtils;

import net.sf.json.JSONObject;

/**
 * 支付宝退款
 * @author hexufeng
 *
 */
@Service("alipayRefundService")
public class AlipayRefundService extends RefundService{

	private static final Logger logger = LoggerFactory.getLogger(AlipayRefundService.class);

	@Autowired
	private PayChannelConfigFeign payChannelConfigFeign;
	@Autowired
    private AliPayConfig aliPayConfig;

	public RefundResponse refundNoPwd(RefundRequest request){
		
		logger.info("****************调用支付宝退款接口开始*******************");

		RefundResponse refundResponse = new RefundResponse();

		Map<String, Object> reqMap = new HashMap<String, Object>();
    	reqMap.put("platformId", request.getPlatformId());
    	reqMap.put("merchantId", request.getMerchantId());
    	reqMap.put("payChannelNo", request.getPayChannelNo());
		Map<String, Object> respMap = payChannelConfigFeign.query(reqMap);
        if(!(boolean) respMap.get("success")){
			refundResponse.setSuccess(false);
			refundResponse.setCode(ResponseCode.PAYCHANNEL_CONFIGURATION_NOTEXIST.getCode());
			refundResponse.setMsg(ResponseCode.PAYCHANNEL_CONFIGURATION_NOTEXIST.getMessage());
			return refundResponse;
		}
        
        @SuppressWarnings("unchecked")
		Map<String, Object> configMap = (Map<String, Object>)respMap.get("payChannelConfigInfo");

		JSONObject json = new JSONObject();
		json.put("out_trade_no", request.getSerialNo());
		json.put("refund_amount ", request.getRefundAmt());
		json.put("out_request_no ", request.getRefundSerialNo());
		String jsonStr = json.toString();
		logger.info("调用支付宝请求参数。。。。。。。{}", jsonStr);

		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",(String)configMap.get("outMerNo"),(String)configMap.get("outMerPrivateKey"),"json","UTF-8",(String)configMap.get("outMerPublicKey"),"RSA2");
		AlipayTradeRefundRequest refundRequest = new AlipayTradeRefundRequest();
		refundRequest.setNotifyUrl(aliPayConfig.getBackCallbackUrl() + "/callBack/aliPay");//退款回调地址
		refundRequest.setBizContent(jsonStr);
		AlipayTradeRefundResponse response;
		try {
			response = alipayClient.execute(refundRequest);
			logger.info("调用支付宝响应参数。。。。。。。{}", EntityUtils.beanToMap(response));
			if(response.isSuccess() && "10000".equals(response.getCode())){
				if("ACQ.TRADE_HAS_SUCCESS".equals(response.getSubCode())){
					refundResponse.setStatus("02");//退款处理中
					refundResponse.setSuccess(true);
					refundResponse.setCode(ResponseCode.OK.getCode());
					refundResponse.setMsg(ResponseCode.OK.getMessage());
				}else{
					refundResponse.setStatus("01");//退款失败
					refundResponse.setErrorMsg(response.getMsg());
					refundResponse.setSuccess(true);
					refundResponse.setCode(ResponseCode.OK.getCode());
					refundResponse.setMsg(ResponseCode.OK.getMessage());
				}
			} else {
				refundResponse.setSuccess(false);
				refundResponse.setCode(ResponseCode.SEND_DATA_FAIL.getCode());
				refundResponse.setMsg(ResponseCode.SEND_DATA_FAIL.getMessage());
			}
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return refundResponse;
	}

}
